/*
 * Copyright (c) www.bugull.com
 */

package com.bugull.farm.app.server.processor;

import org.apache.logging.log4j.*;
import com.bugull.farm.core.frame.structure.Frame;
import com.bugull.farm.core.handler.Processor;
import com.bugull.farm.core.store.Device;
import com.bugull.farm.core.store.SoftVersion;
import com.bugull.farm.core.utils.ByteUtil;
import com.bugull.farm.core.utils.StringUtil;
import com.bugull.mongo.BuguDao;
import com.bugull.mongo.cache.DaoCache;

import io.netty.channel.ChannelHandlerContext;

/**
 * For command: CMD_APP_SOFT_VERSION
 * 
 * @author Frank Wen(xbwen@hotmail.com)
 */
public class SoftVersionProcessor implements Processor {
	private final Logger logger = LogManager.getLogger(SoftVersionProcessor.class);
    @Override
    public void process(ChannelHandlerContext ctx, Frame frame) throws Exception{
    	
        String mac = frame.getHexStr("mac");
        String softVersion = frame.getASCIIStr("sver");
        String url = "http://";
        
        BuguDao<Device> deviceDao = DaoCache.getInstance().get(Device.class);
        Device device = deviceDao.findOne("macAddress", mac);
        if(device != null){
            String companyCode = device.getCompanyCode();
            String deviceType = device.getDeviceType();
            if(!StringUtil.isEmpty(companyCode) && !StringUtil.isEmpty(deviceType)){
                BuguDao<SoftVersion> versionDao = DaoCache.getInstance().get(SoftVersion.class);
                SoftVersion sv = versionDao.query().is("companyCode", companyCode).is("deviceType", deviceType).result();
                if(sv != null){
                    if(!StringUtil.isEmpty(sv.getVersion())){
                        softVersion = sv.getVersion();
                    }
                    if(!StringUtil.isEmpty(sv.getUrl())){
                        url = sv.getUrl();
                    }
                }
            }
        }
        frame.setByte("slen", softVersion.length());
        frame.setASCIIBytes("sver", softVersion);
        frame.setByte("urllen", url.length());
        frame.setASCIIBytes("url", url);
        ctx.writeAndFlush(frame.getFastResponse());
    }

}
